const path = require('path');
const fse = require('fs-extra');
const log = require('./log');

module.exports = function({rootDir = process.cwd(), commandArgs={}} = {}){
    const { config } = commandArgs;
    let buildConfigPath = '';
    let userConfig = {};
    
    if (config) {
      buildConfigPath = path.isAbsolute(config) ? config : path.resolve(rootDir, config);
    } else {
      buildConfigPath = path.resolve(rootDir, 'builder.config.js');
    }
    
    if (buildConfigPath && fse.existsSync(buildConfigPath)) {
        try {
            userConfig = require(buildConfigPath);
        } catch (err) {
            log.error(`Fail to load config file ${buildConfigPath}, use default config instead`);
            console.error(err);
            process.exit(1);
        }
    }
    return userConfig;
}